--[[
	Copyright (c) 2012 Eyal Shilony

	Permission is hereby granted, free of charge, to any person obtaining
	a copy of this software and associated documentation files (the
	"Software"), to deal in the Software without restriction, including
	without limitation the rights to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to
	permit persons to whom the Software is furnished to do so, subject to
	the following conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN 
	
	NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
	LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
	OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
	WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

	-- Provides a friendlier methodology to add options to the Blizzard Interface Options panel using AceConfig.
]]

assert(LibStub, "AceConfigRegistrar-1.0 requires LibStub")

__AceConfigRegistrarCurrentAddonName = ...
local lib, minor = LibStub:NewLibrary("AceConfigRegistrar-1.0", 0)
if not lib then return end
minor = minor or 0

local config = LibStub("AceConfig-3.0")
local dialog = LibStub("AceConfigDialog-3.0")

local function fixOptionsTable(source, argsfix)
	local dest = { }
	for k, v in pairs(source) do
		if type(v) ~= "table" then
			if tonumber(k) then 
				tinsert(dest, k, v)
			else
				dest[k] = v
			end
		else
			if tonumber(k) and argsfix then
				local key = tostring(k);
				dest[key] = fixOptionsTable(v)
				dest[key].order = k
			elseif k == "args" then
				dest[k] = fixOptionsTable(v, true)
			else
				dest[k] = fixOptionsTable(v)
			end
		end
	end
	return dest
end

local parentName
function lib:RegisterOptions(table, legacyOptionsFormat)
	if table and table.name then
		if not legacyOptionsFormat then
			table = fixOptionsTable(table)
		end
		local name = parentName and __AceConfigRegistrarCurrentAddonName .. "_" .. table.name or __AceConfigRegistrarCurrentAddonName
		config:RegisterOptionsTable(name, table)
		if not parentName then
			parentName = table.name
			dialog:AddToBlizOptions(name, table.name)
		else
			dialog:AddToBlizOptions(name, table.name, parentName)
		end
	end
end